const query = require('../../utils/query')

// 修改所编辑的文章数据
exports.changeArticle = async (newArticleData) => {
  let { article_id, title, cover, category_id, tag_ids, content } =
    newArticleData
  console.log(article_id, title, cover, category_id, tag_ids, content)

  let sql = `
    UPDATE article 
    SET 
      title = '${title}',
      cover = '${cover}',
      category_id = ${category_id},
      tag_ids = '${tag_ids}',
      content = '${content}'
    WHERE 
      article_id = ${article_id}
  `
  let result = await query(sql)
  return result
}

// 获取所编辑的文章数据
exports.getEditArticle = async (article_id) => {
  let sql = `select article_id,title, cover, category_id, tag_ids, content from article where article_id = ${article_id} `
  let result = await query(sql)
  return result[0]
}

// 获取标签分类数据
exports.getTagArticle = async () => {
  let sql = `SELECT 
    t.tag_name as name,
    COUNT(a.article_id) AS value
FROM 
    tag t
LEFT JOIN 
    article a ON FIND_IN_SET(t.tag_id, a.tag_ids) > 0
GROUP BY 
    t.tag_id, t.tag_name`
  let result = await query(sql)
  return result
}

// 获取文章分类数据
exports.getCategoryArticle = async () => {
  let sql = `SELECT 
    c.category_name,
    COUNT(a.article_id) as count
    FROM category c
    LEFT JOIN 
    article a ON c.category_id = a.category_id
    GROUP BY 
    c.category_id`
  let result = await query(sql)
  return result
}

// 添加文章
exports.addArticle = async (newArticleData) => {
  let { title, content, tag_ids, category_id, cover } = newArticleData
  let sql = `insert into article(title, content, tag_ids, category_id, cover) 
        values('${title}', '${content}', '${tag_ids}', ${category_id}, '${cover}')`
  let result = await query(sql)
  return result
}

// 获取标签数量
exports.getCount = async (title) => {
  let sql = `select count(article_id) as count from article where 1 `

  if (title) {
    sql += ` and title like '%${title}%'`
  }

  let result = await query(sql)
  return result[0].count
}

// 获取文章数据
exports.getArticle = async (page, pagesize, title) => {
  let offset = (page - 1) * pagesize

  let sql = `select t1.article_id, t1.title, t1.content, t1.tag_ids, t1.category_id, t1.cover, t1.category_id, t2.category_name from article
  t1 left join category t2 on t1.category_id = t2.category_id where 1`

  if (title) {
    sql += ` and title like '%${title}%'`
  }

  sql += ` limit ${offset}, ${pagesize}`
  let result = await query(sql)

  return result
}
